const path = require('path')
const { fileToJson, jsonToFile } = require('../utils/index')

class UserController {
  static async getUsers() {
    const users = await fileToJson(path.resolve(__dirname, '../users.json'))
    return users || []
  }

  static async updateUsers(users) {
    await jsonToFile(path.resolve(__dirname, '../users.json'), JSON.stringify(users))
  }

  static async getUserById(ctx) {
    const { id } = ctx.request.query
    if (!id) {
      ctx.body = {
        code: 40001,
        data: null,
        msg: "'ip' is required."
      }
    }

    const users = await UserController.getUsers()
    const matchUser = users.find(v => v.id === id)

    ctx.body = !!matchUser
      ? {
          code: 20000,
          data: matchUser,
          msg: 'success'
        }
      : {
          code: 20001,
          data: null,
          msg: 'not finded'
        }
  }

  static async insetUser(ctx) {
    const { id, name, avatar } = ctx.request.body
    const users = await UserController.getUsers()
    const hadInseted = users.some(v => v.id === id)

    if (hadInseted) {
      ctx.body = { code: 20002, data: null, msg: 'had inseted' }
    } else {
      users.push({ id, name, avatar })
      await UserController.updateUsers(users)
      ctx.body = { code: 20000, data: null, msg: 'inset success' }
    }
  }

  static async updateUser(ctx) {
    const { id, name, avatar } = ctx.request.body
    const users = await UserController.getUsers()

    const hadFinded = users.some(v => v.id === id)
    if (!hadFinded) {
      ctx.body = { code: 20002, data: null, msg: 'user not finded' }
    } else {
      const matchIndex = users.findIndex(v => v.id === id)
      users.splice(matchIndex, 1, { id, name, avatar })
      await UserController.updateUsers(users)
      ctx.body = { code: 20000, data: null, msg: 'update success' }
    }
  }
}

module.exports = UserController
